<template>
  <div>
    <el-container style="max-width: 960px">
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              :loading="listLoading"
              @click="handleSearch"
            >搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create')"
          >添加分类</el-button>
        </el-row>
      </el-header>

      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @sort-change="handleSort"
        >
          <el-table-column
            prop="name"
            label="分类名称"
            width="300"
            sortable="custom"
          />
          <el-table-column
            prop="create_at"
            label="创建时间"
            width="180"
            sortable="custom"
          />

          <el-table-column
            align="center"
            label="操作"
            width="200"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-edit"
                type="warning"
                plain
                @click="handleAction('edit', scope.row)"
              >修改</el-button>
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-delete"
                type="danger"
                plain
                @click="handleAction('delete', scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="data.length"
          background
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="mt-pagination"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="categoryForm"
        :model="temp"
        label-position="left"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item
          label="分类名称"
          prop="name"
        >
          <el-input v-model="temp.name" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button
          :type="action !== 'delete' ? 'primary' : 'danger'"
          @click="confirm"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmm'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'CrmCustomerCategory',
  data() {
    return {
      table_name: 'CRMCustomerCategory',
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // 分页
      pagesize: 10,
      page: 1,
      total: 0,

      // 弹窗相关
      action: null,
      title: '',
      width: '640px',
      innerDialogVisible: false,

      // 表单数据
      temp: {
        name: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 2000, message: '长度在 1 到 2000 个字符', trigger: 'blur' }
        ],
        project: [
          { required: true, message: '请选择所属项目', trigger: 'change' }
        ]
      }
    }
  },

  created() {
    this.getList()
  },

  methods: {
    // 重置表单
    resetTemp() {
      this.temp = {
        name: ''
      }
    },

    // 获取分类列表
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        table_name: this.table_name,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(err => {
          console.error(err)
          this.listLoading = false
        })
    },

    // 处理操作按钮点击
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = '添加分类'
          this.resetTemp()
          this.innerDialogVisible = true
          break

        case 'delete':
          this.title = `确认要删除分类: ${row.name}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break

        case 'edit':
          this.title = `修改分类: ${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },

    // 确认操作
    confirm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          const _data = this.temp
          _data.table_name = this.table_name

          switch (this.action) {
            case 'create':
              Post(_data).then(response => {
                this.innerDialogVisible = false
                this.getList()
                this.notify('添加成功')
              })
              break

            case 'delete':
              Delete(_data.id, _data).then(response => {
                this.innerDialogVisible = false
                this.getList()
                this.notify('删除成功')
              })
              break

            case 'edit':
              Put(_data.id, _data).then(response => {
                this.innerDialogVisible = false
                this.getList()
                this.notify('更新成功')
              })
              break
          }
        }
      })
    },

    // 提示信息
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },

    // 处理页码变化
    handlePageChange(val) {
      this.page = val
      this.getList()
    },

    // 处理搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },

    // 处理排序
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },

    // 滚动到顶部
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
